from lib.ZSprite import ZSprite
from res.fun import _create_image, _get_center_x, _get_bottom, _out_screen
from res.glo import src
from res.conf import tick, planefire, planespeed, planehealth
from pygame.locals import K_a, K_w, K_s, K_d
from assets.script.bullet import Bullet


class Plane(ZSprite):
    def __init__(self):
        super(Plane, self).__init__()
        self.health = planehealth
        self.image = _create_image(src['image']['plane'])
        self.rect = self.image.get_rect()
        self.rect.topleft = _get_center_x(self.rect.width), _get_bottom(self.rect.height)
        self.speed = planespeed
        self.bullets = list()
        self.firtime = planefire
        self.curtime = 0.00

    def draw(self):
        if self.isRunning:
            self.fire()
            self.screen.blit(self.image, self.rect.topleft)

    def update(self, keys):
        if self.isRunning:
            for bullet in self.bullets:
                bullet.update()
            self.planecontrol(keys)

    def planecontrol(self, keys):
        if keys[K_s]: self.move('down')
        if keys[K_d]: self.move('right')
        if keys[K_a]: self.move('left')
        if keys[K_w]: self.move('up')

    def bulletdraw(self):
        for bullet in self.bullets:
            if _out_screen(bullet.rect):
                self.bullets.remove(bullet)
            bullet.draw()

    def fire(self):
        s = tick / 1000.00
        self.curtime += s
        if self.curtime >= self.firtime:
            bulletleft = Bullet()
            bulletleft._pos = self.rect.x + 17, self.rect.y - bulletleft.rect.height + 23
            bulletright = Bullet()
            bulletright._pos = self.rect.x + self.rect.width - 19, self.rect.y - bulletright.rect.height + 23
            self.bullets.append(bulletleft)
            self.bullets.append(bulletright)
            self.curtime = 0.00
        self.bulletdraw()

    def hit(self, sprite):
        self.health -= sprite.hitdamage
        if self.health <= 0:
            self.isRunning = False

    def reset(self):
        self.health = planehealth
        self.isRunning = True
        self.rect.topleft = _get_center_x(self.rect.width), _get_bottom(self.rect.height)
        self.speed = planespeed
        self.bullets = []
        self.firtime = planefire
        self.curtime = 0.00
